﻿using System;
using System.Linq;
using log4net.Config;
using NHibernate.Tool.hbm2ddl;
using NLite.Cfg;
using NLite.NHPersistence;
using NLite.Persistence;
using NUnit.Framework;
using NLite;
using NLite.Mini;
namespace NLite.NHPersistenceTest
{
    [TestFixture]
    public abstract class TestBase
    {
        protected INhibernateSessionFactory Factory;
        DbSessionFactoryProvider FactoryProvider;
        Configuration cfg = new Configuration();
        protected INhibernateSession Session;
     
        [TestFixtureSetUp]
        public void FixtureSetUp()
        {
            XmlConfigurator.Configure();
            cfg.Configure();
            Factory = NhibernateSessionFactory.Configure();

            ServiceRegistry
             .Current.Register(typeof(DbSessionFactoryProvider))
             .Register<NHQueryExtension>();

            FactoryProvider = ServiceLocator.Get<DbSessionFactoryProvider>();
            FactoryProvider.Register(Factory);

            var config = Factory.Cfg;
            SchemaExport export = new SchemaExport(config);
            export.Create(false, true);

            NLite.ServiceRegistry.Compose(this);
        }

        protected IRepository<UserInfo, Guid> repository;
        protected IQueryable<UserInfo> query;

        [SetUp]
        public void SetUp()
        {
            Session = Factory.OpenSession() as INhibernateSession;
            this.repository = Session.CreateRepository<UserInfo, Guid>();
            this.query = Session.Query<UserInfo>();
            OnInit();
        }

        protected virtual void OnInit()
        {
        }

        [TearDown]
        public void TearDown()
        {
            Session.Close();
        }

        [TestFixtureTearDown]
        public void Destory()
        {
            FactoryProvider.Dispose();
            cfg.Clear();
        }
    }
}
